#include "str.h"

vector<string> lib::common::str::explode(const string &delimiter, const string &str) {
    vector<string> arr;

    int strleng = str.length();
    int delleng = delimiter.length();
    if (delleng == 0)
        return arr; //no change

    int i = 0;
    int k = 0;
    while (i < strleng) {
        int j = 0;
        while (i + j < strleng && j < delleng && str[i + j] == delimiter[j])
            j++;
        if (j == delleng)//found delimiter
        {
            arr.push_back(str.substr(k, i - k));
            i += delleng;
            k = i;
        } else {
            i++;
        }
    }
    arr.push_back(str.substr(k, i - k));
    return arr;
}

bool lib::common::str::startswith(string prefix, string str){
    if (str.length() >= prefix.length()){
        return (0 == str.compare(0, prefix.length(), prefix));
    }else{
        return false;
    }
}

bool lib::common::str::endswith(string suffix, string str){
    if (str.length() >= suffix.length()) {
        return (0 == str.compare (str.length() - suffix.length(), suffix.length(), suffix));
    } else {
        return false;
    }
}

bool lib::common::str::contains(string needle, string target) {
    unsigned found = target.find(needle);
    return found != string::npos;
}

int lib::common::str::to_int(string value) {
    stringstream ss(value);
    int result;
    ss >> result;
    return result;
}

string lib::common::str::to_str(int value) {
    ostringstream ss;
    ss << value;
    return ss.str();
}

string lib::common::str::replace(string str, const string& from, const string& to) {
    size_t start_pos = str.find(from);
    if (start_pos == string::npos)
        return str;
    return str.replace(start_pos, from.length(), to);
}

string lib::common::str::replace_all(string str, const string& from, const string& to) {
    if (from.empty())
        return str;
    size_t start_pos = 0;
    while ((start_pos = str.find(from, start_pos)) != string::npos) {
        str = str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
    return str;
}

string lib::common::str::trim(string str) {
    str.erase(0, str.find_first_not_of(' ')); //prefixing spaces
    str.erase(str.find_last_not_of(' ') + 1); //surfixing spaces
    return str;
}